/**
 * 
 */
package com.rd.sys.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import baseproj.common.util.DateTimeUtils;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.crypto.BASE64;
import com.rd.sys.service.sys.user.impl.UserInfoServiceException;

/**
 * The Class CommonUtils.
 * 
 * @author
 */
public class CommonUtils {

    /** The Constant log. */
    protected static final Logger log = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * Handle date time.
     * 
     * @param dateStr
     *            the date str
     * @param format
     *            the format
     * @return the string
     * @version
     */
    public static String handleDateTime(String dateStr, String format) {
        Date date;
        try {
            date = DateTimeUtils.parseDate(dateStr);
        } catch (Exception e) {
            return "";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    /**
     * Handle date time.
     * 
     * @param dateStr
     *            the date str
     * @return the string
     * @version
     */
    public static String handleDateTime(String dateStr) {
        Date date;
        try {
            date = DateTimeUtils.parseDate(dateStr);
        } catch (Exception e) {
            return "";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    /**
     * 获取客户端IP地址.
     * 
     * @param request
     *            the request
     * @return the ip addr
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 第一个参数里的占位符用第二个数组参数替换，返回替换后的字符串.
     * 
     * @param str
     *            the str
     * @param ele
     *            the ele
     * @return the string
     * @version
     */
    public static String format(String str, String[] ele) {
        if (str == null) {
            return "";
        }
        char[] temp = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        int j = 0;
        int length = temp.length;
        int i = 0;
        while (i < length) {
            if (temp[i] == '?') {
                if (i < temp.length - 1 && temp[i + 1] == '?') {
                    sb.append("?");
                    i += 2;
                } else {
                    if (j < ele.length) {
                        sb.append(ele[j] == null ? "" : ele[j]);
                    } else {
                        break;
                    }
                    j++;
                    i++;
                }
            } else {
                sb.append(temp[i]);
                i++;
            }
        }
        return sb.toString();
    }

    /**
     * Substr.
     * 
     * @param content
     *            the content
     * @param length
     *            the length
     * @return the string
     * @version
     */
    public static String substr(String content, int length) {
        if (StringUtils.isBlank(content)) {
            return "";
        }

        return content.substring(0, length);
    }

    /**
     * Gets the chinese len.
     * 
     * @param value
     *            the value
     * @return the chinese len
     */
    public static int getChineseLen(String value) {
        Pattern p = Pattern.compile("[^\\x00-\\x7F]");
        Matcher m = p.matcher(value);
        int chinanum = 0;
        while (m.find()) {
            ++chinanum;
        }

        return value.length() + chinanum;
    }

    /**
     * 显示固定长度的字段信息，多余的用...填充.
     * 
     * @param content
     *            the content
     * @param len
     *            the len
     * @return the string
     * @version
     */
    public static String subContent(String content, int len) {
        if (null != content && content.trim().length() > 0) {
            if (len > content.length()) {
                return content;
            }
            return content.substring(0, len) + "...";
        }
        return "";
    }

    /**
     * 默认截取显示15个字节的字段信息.
     * 
     * @param content
     *            the content
     * @return the string
     * @version
     */
    public static String subContent(String content) {
        return CommonUtils.subContent(content, 15);
    }

    /**
     * 生成用户安全基本密钥.
     * 
     * @return the string
     * @version
     */
    public static String genBaseKey() throws Exception {
        String randomStr = "";
        try {
            randomStr = RandomStringUtils.randomAlphanumeric(CommonConstants.UserConstats.USER_SECURITY_BASEKEY_LENGTH);
            randomStr = randomStr.toUpperCase();
            randomStr = BASE64.encode(randomStr);
        } catch (Exception e) {
            throw new UserInfoServiceException(UserInfoServiceException.CREATE_BASE_KEY_ERROR);
        }
        return randomStr;
    }

    /**
     * 生成初始密码
     * 
     * @return
     */
    public static String genInitalPassword() {
        String password = RandomStringUtils
                .randomAlphanumeric(CommonConstants.UserConstats.USER_INITIAL_PASSWORD_LENGTH);
        return password;
    }

    /**
     * 判断是否是使用当前user.dir目录
     * 
     * @param config
     * @return
     */
    public static String judgeConfigPath(String config) {
        if (config.startsWith("user.dir")) { // 是，就替换成实际的当前目录地址
            return config.replace("user.dir", System.getProperty("user.dir"));
        } else { // 否,就使用配置的地址
            return config;
        }
    }
}
